package com.chance.cc.crawler.development.scripts.autohome.chejiahao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequest;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.CategoryTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.*;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AutoVMCommonField.*;

/**
 * @author lt
 * @version 1.0
 * @date 2020-11-24 18:18:06
 * @email okprog@sina.com
 */
public class AutoHomeCheVideoCrawlerScript extends CrawlerCommonScript {

    private Logger logger = LoggerFactory.getLogger(AutoHomeCheVideoCrawlerScript.class);

    private static final String listUrlFormat = "https://chejiahao.autohome.com.cn/Default/IndexMore?infotype=%s&pageId=%s&pageIdentity=1";
    private static final String commentUrlFormat = "https://reply.autohome.com.cn/api/comments/show.json?count=50&appid=21&replydata=1&order=0&page=%s&id=%s";
    private static final String commentCountUrlFormat = "https://reply.autohome.com.cn/api/QueryComment/CountsByObjIds?_appid=cms&appid=21&dataType=json&objids=%s";
    private static final String likesUrlFormat = "https://reply.autohome.com.cn/api/like/listcount.json?_appid=m&appid=21&liketype=1&ids=%5B%7B%22objid%22%3A#objId%2C%22secobj%22%3A%22%22%7D%5D&datatype=json";

    private static final String indexRegex = "https?://chejiahao\\.autohome\\.com\\.cn/\\?infotype=\\d*";
    private static final String listUrlRegex = "https?://chejiahao\\.autohome\\.com\\.cn/Default/IndexMore\\?infotype=\\d*&pageId=\\d*&pageIdentity=\\d*";
    private static final String articleUrlRegex = "https?://chejiahao\\.autohome\\.com\\.cn/info/\\d*";
    private static final String commentRegex = "https://reply\\.autohome\\.com\\.cn/api/comments/show\\.json\\?count=50&appid=21&replydata=1&order=0&page=\\d*&id=\\d*";
    private static final String commentCountUrlRegex = "https://reply\\.autohome\\.com\\.cn/api/QueryComment/CountsByObjIds\\?_appid=cms&appid=21&dataType=json&objids=\\d*";
    private static final String likesUrlRegex = "https://reply\\.autohome\\.com\\.cn/api/like/listcount\\.json\\?\\S*";


    private static final String scriptSite = "che_video";
    private static final String CHE_VIDEO_BASE_URL = "https://chejiahao.autohome.com.cn";

    private static final long ONE_SECOND = 1000L;
    private static final long ONE_MINUTE = 60000L;
    private static final long ONE_HOUR = 3600000L;
    private static final long ONE_DAY = 86400000L;

    @Override
    public String domain() {
        return "autohome";
    }

    @Override
    public void initUrlRegulars() {
        addUrlRegular(indexRegex);
        addUrlRegular(listUrlRegex);
        addUrlRegular(articleUrlRegex);
        addUrlRegular(commentRegex);
        addUrlRegular(commentCountUrlRegex);
        addUrlRegular(likesUrlRegex);
    }

    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        CategoryTag categoryTag = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag();
        String crawlerSite = categoryTag.getKVTagStrVal("site");
        return false;
    }

    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        int statusCode = httpPage.getStatusCode();
        String lastRequestUrl = lastRequest.getUrl();
        if (StringUtils.isBlank(httpPage.getRawText()) || !httpPage.isDownloadSuccess() || (statusCode != 200 && statusCode != 404)){
            parsedLinks.add(crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            crawlerRequestRecord.tagsCreator().requestTags().removeRequestType(CrawlerEnum.CrawlerRequestType.filter);
            return parsedLinks;
        }
        if (statusCode == 404){
            logger.info("页面不存在: " + statusCode);
            return null;
        }
        CrawlerBusinessTags bizTags = crawlerRequestRecord.tagsCreator().bizTags();
        CategoryTag categoryTag = bizTags.getCategoryTag();
        // 首页链接需要初始翻页链接 解析当页列表
        if (lastRequestUrl.matches(indexRegex) || lastRequestUrl.matches(listUrlRegex)){
            List<Selectable> selectables = httpPage.getHtml().xpath("//div[@pageid]").nodes();
            if (!selectables.isEmpty()){
                Selectable lastNode = selectables.get(selectables.size() - 1);
                String pageId = lastNode.xpath("./@pageid").get();

                String infoType = "";
                Map<String,Object> extras = null;
                if (lastRequestUrl.matches(indexRegex)){
                    infoType = lastRequestUrl.split("infotype=")[1];
                    extras = new HashMap<>();
                    extras.put("infoType",infoType);
                }
                if (lastRequestUrl.matches(listUrlRegex)){
                    extras = lastRequest.getExtras();
                    infoType = (String) extras.get("infoType");
                }

                String nextPageUrl = String.format(listUrlFormat,infoType,pageId);

                CrawlerRequestRecord listItemRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(crawlerRequestRecord)
                        .recordKey(nextPageUrl)
                        .httpUrl(nextPageUrl)
                        .releaseTime(System.currentTimeMillis())
                        .copyBizTags()
                        .copyScheduleTags()
                        .build();
                HttpRequest httpRequest = listItemRecord.getHttpRequest();
                httpRequest.setExtras(extras);
                httpRequest.addHeader("origin","https://chejiahao.autohome.com.cn");
                httpRequest.addHeader("referer","https://chejiahao.autohome.com.cn/?infotype=3");
                httpRequest.addHeader("user-agent",getRandomUA());
                parsedLinks.add(listItemRecord);

                for (Selectable selectable : selectables) {
                    String articleKey = selectable.xpath("./@data-infoid").get();
                    String itemUrl = CHE_VIDEO_BASE_URL + "/info/" + articleKey;
                    String views = selectable.xpath("./div[@class=\"userInfo\"]/div[@class=\"info fn-right\"]/span[1]/text()").get();
                    String pubTime = selectable.xpath("./div[@class=\"userInfo\"]/div[@class=\"info fn-right\"]/span[4]/text()").get();
                    String regex_1 = "\\d{2}-\\d{2} \\d{2}:\\d{2}";
                    if (pubTime.matches(regex_1)){
                        Calendar calendar = Calendar.getInstance();
                        int year = calendar.get(Calendar.YEAR);
                        pubTime = year + "-" + pubTime;
                    }
                    Map<String,Object> extrasEach = new HashMap<>();
                    extrasEach.put("articleKey",articleKey);
                    extrasEach.put("views",views);
                    try {
                        long releaseTime = DateUtils.parseDate(pubTime,"yyyy-MM-dd HH:mm").getTime();
                        CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                                .itemPageRequest(crawlerRequestRecord)
                                .recordKey(itemUrl)
                                .httpUrl(itemUrl)
                                .releaseTime(releaseTime)
                                .resultLabelTag(article)
                                .resultLabelTag(interaction)
                                .copyBizTags()
                                .copyScheduleTags()
                                .build();
                        itemRecord.getHttpRequest().setExtras(extrasEach);
                        itemRecord.getHttpRequest().addHeader("user-agent",getRandomUA());
                        parsedLinks.add(itemRecord);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),"parse date error");
                    }
                }
            }
            return parsedLinks;
        }
        // 文章链接产生 内循环:点赞,评论数 外循环:评论列表
        if (lastRequestUrl.matches(articleUrlRegex)){
            if (httpPage.getRawText().contains("您要浏览的页面暂时无法访问或不存在")){
                return parsedLinks;
            }
            if (httpPage.getRawText().contains("尊敬的用户您好，您的访问出现异常，为确认本次访问为正常用户行为")){
                parsedLinks.add(crawlerRequestRecord);
                crawlerRequestRecord.setNeedWashPage(false);
                crawlerRequestRecord.tagsCreator().requestTags().removeRequestType(CrawlerEnum.CrawlerRequestType.filter);
                logger.warn("文章详情: {} 访问出现异常，需要重新请求",httpPage.getRequest().getUrl());
                return parsedLinks;
            }
            crawlerRequestRecord.setNeedWashPage(true);
            Map<String, Object> extras = lastRequest.getExtras();
            String articleKey = (String)extras.get("articleKey");
            String likesUrl = likesUrlFormat.replace("#objId",articleKey);
            extras.put("articleUrl",lastRequestUrl);
            CrawlerRequestRecord itemInternalLikesRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRequestRecord)
                    .recordKey(likesUrl)
                    .httpUrl(likesUrl)
                    .releaseTime(crawlerRequestRecord.getReleaseTime())
                    .needParsed(false)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                    .copyBizTags()
                    .copyScheduleTags()
                    .build();
            itemInternalLikesRecord.getHttpRequest().setExtras(extras);
            parsedLinks.add(itemInternalLikesRecord);

            //评论数接口
            String commentCountUrl = String.format(commentCountUrlFormat,articleKey);
            CrawlerRequestRecord commentCountRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRequestRecord)
                    .recordKey(commentCountUrl)
                    .httpUrl(commentCountUrl)
                    .releaseTime(crawlerRequestRecord.getReleaseTime())
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                    .build();
            commentCountRecord.getHttpRequest().setExtras(extras);
            parsedLinks.add(commentCountRecord);

            //评论列表链接
            String commentUrl = String.format(commentUrlFormat,1,articleKey);
            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRequestRecord)
                    .recordKey(commentUrl)
                    .httpUrl(commentUrl)
                    .releaseTime(crawlerRequestRecord.getReleaseTime())
                    .resultLabelTag(comment)
                    .resultLabelTag(interaction)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.turnPageItem)
                    .copyBizTags()
                    .copyScheduleTags()
                    .build();
            commentRecord.getHttpRequest().setExtras(extras);
            parsedLinks.add(commentRecord);
            return parsedLinks;
        }
        if (lastRequestUrl.matches(commentRegex)){
            //根据返回的json结果计算下一页
            Map<String, Object> extras = lastRequest.getExtras();
            String articleKey = (String) extras.get("articleKey");
            JSONObject jsonObject = JSONObject.parseObject(httpPage.getRawText());
            int currentPage = jsonObject.getIntValue("page");
            int commentCount = jsonObject.getIntValue("commentcount");
            int maxPage = (int) Math.ceil(commentCount / 50.0);
            if (currentPage < maxPage){
                String commentUrl = String.format(commentUrlFormat,(currentPage + 1), articleKey);
                CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .recordKey(commentUrl)
                        .httpUrl(commentUrl)
                        .releaseTime(crawlerRequestRecord.getReleaseTime())
                        .resultLabelTag(comment)
                        .resultLabelTag(interaction)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.turnPageItem)
                        .copyBizTags()
                        .copyScheduleTags()
                        .build();

                commentRecord.getHttpRequest().setExtras(extras);
                parsedLinks.add(commentRecord);
            }
            return parsedLinks;
        }
        return null;
    }

    @Override
    public void afterInternalDownload(CrawlerRequestRecord crawlerRecord, List<CrawlerRequestRecord> internalDownloadRecords, List<CrawlerRequestRecord> links) {
        HttpRequest lastRequest = crawlerRecord.getHttpRequest();
        String lastRequestUrl = lastRequest.getUrl();
        Map<String, Object> extras = lastRequest.getExtras();
        if (lastRequestUrl.matches(articleUrlRegex)){
            for (CrawlerRequestRecord internalDownloadRecord : internalDownloadRecords) {
                HttpRequest downloadRecordHttpRequest = internalDownloadRecord.getHttpRequest();
                String downloadRecordHttpRequestUrl = downloadRecordHttpRequest.getUrl();
                HttpPage internalDownloadPage = internalDownloadRecord.getInternalDownloadPage();
                // 获取点赞数
                if (downloadRecordHttpRequestUrl.matches(likesUrlRegex)){
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(internalDownloadPage.getRawText());
                        int returnCode = jsonObject.getIntValue("returncode");
                        if (0 == returnCode){
                            JSONObject result = (JSONObject) jsonObject.getJSONArray("result").get(0);
                            String likes = result.getString("count");
                            extras.put("likes",likes);
                        }
                    } catch (Exception e) {
                        extras.put("likes","0");
                    }
                }
                // 获取评论数
                if (downloadRecordHttpRequestUrl.matches(commentCountUrlRegex)){
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(internalDownloadPage.getRawText());
                        int returnCode = jsonObject.getIntValue("returncode");
                        if (0 == returnCode){
                            JSONObject result = jsonObject.getJSONObject("result");
                            JSONObject sum = result.getJSONObject("sum");
                            String comments = sum.getString("sumreplycount");
                            extras.put("comments",comments);
                        }
                    } catch (Exception e) {
                        extras.put("comments","0");
                    }
                }
            }
        }
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        if (crawlerRequestRecord.tagsCreator().resultTags().hasDataType(article)){
            crawlerDataList.addAll(washArticle(crawlerRequestRecord, httpPage));
        }

        if (crawlerRequestRecord.tagsCreator().resultTags().hasDataType(interaction)){
            crawlerDataList.addAll(washInteraction(crawlerRequestRecord,httpPage));
        }

        if (crawlerRequestRecord.tagsCreator().resultTags().hasDataType(comment)){
            crawlerDataList.addAll(washComment(crawlerRequestRecord,httpPage));
        }

        return crawlerDataList;
    }


    private List<CrawlerData> washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerArticleDataList = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        Map<String, Object> extras = lastRequest.getExtras();
        String author = httpPage.getHtml().xpath("//div[@class=\"articleTag\"]/span[1]/text()").get();
        String follows = httpPage.getHtml().xpath("//div[@class=\"num\"]/span[1]/text()").get();
        if (StringUtils.isBlank(follows)){
            follows = "0";
        }
        if (follows.endsWith("关注")){
            follows = follows.replace("关注","");
        }
        if (follows.contains("万")){
            follows = follows.split("万")[0];
            follows = String.valueOf(Double.parseDouble(follows) * 10000);
        }

        String authorUrl = httpPage.getHtml().xpath("//div[@class=\"name text-overflow\"]/a/@href").get();
        String authorId = "";
        if (StringUtils.isNotBlank(authorUrl)){
            authorId = authorUrl.split("Authors/")[1].split("#")[0];
        }

        String title = httpPage.getHtml().xpath("//div[@class=\"title\"]/text() | //div[@class=\"title \"]/text()").get();
        if (null != title){
            title = unescapeHtml2J(title);
        }

        List<String> allContents = httpPage.getHtml().xpath("//div[@class=\"videoText\"]//p//text()").all();
        StringBuffer sbContent = new StringBuffer();
        for (String s : allContents) {
            sbContent = sbContent.append(s).append(" ");
        }
        String content = sbContent.toString();
        if (null != content){
            content = unescapeHtml2J(content);
        }
        String audioUrl = httpPage.getHtml().xpath("//video/@src").get();
        List<String> categories = httpPage.getHtml().xpath("//div[@class=\"tagBotV\"]//span/text()").all();
        if (null != categories && !categories.isEmpty()){
            crawlerRequestRecord.tagsCreator().bizTags().addCustomKV("article_tag",categories);
        }
        try {
            String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");

            CrawlerData crawlerArticleData = CrawlerData.builder()
                    .data(crawlerRequestRecord,httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, article.enumVal(), (String)extras.get("articleKey")))
                    .url(lastRequest.getUrl())
                    .releaseTime(crawlerRequestRecord.getReleaseTime())
                    .addContentKV(Field_Author, author)
                    .addContentKV(Field_Author_Id, authorId)
                    .addContentKV(Field_Author_Follows, follows)
                    .addContentKV(Field_Title, title == null ? "" : title)
                    .addContentKV(Field_Content, content)
                    .addContentKV(Field_Audios, audioUrl)
                    .resultLabelTag(article)
                    .build();
            crawlerArticleData.tagsCreator().bizTags().addSiteBiz("hao_video");
            crawlerArticleDataList.add(crawlerArticleData);
        } catch (Exception e) {
            logger.error(e.getMessage(),"wash data error");
        }
        return crawlerArticleDataList;
    }

    private List<CrawlerData> washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerInteractionDataList = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        String lastRequestUrl = lastRequest.getUrl();
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");

        Map<String, Object> extras = lastRequest.getExtras();
        if (lastRequestUrl.matches(articleUrlRegex)){
            String articleKey = (String)extras.get("articleKey");
            String views = (String)extras.get("views");
            if (views.contains("万")){
                views = views.replace("万","");
                if (views.contains(".")){
                    views = views.replace(".","") + "000";
                }else {
                    views = views + "0000";
                }

            }
            String comments = (String)extras.get("comments");
            String likes = (String)extras.get("likes");
            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, interaction.enumVal(), articleKey))
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, article.enumVal(), articleKey))
                    .url(lastRequest.getUrl())
                    .releaseTime(crawlerRequestRecord.getReleaseTime())
                    .addContentKV(Field_I_Comments,comments)
                    .addContentKV(Field_I_Views,views)
                    .addContentKV(Field_I_Likes,likes)
                    .resultLabelTag(interaction)
                    .build();
            crawlerData.tagsCreator().bizTags().addSiteBiz("hao_video");
            crawlerInteractionDataList.add(crawlerData);
        }
        if (lastRequestUrl.matches(commentRegex)){
            JSONObject jsonObject = JSONObject.parseObject(httpPage.getRawText());
            JSONArray commentList = jsonObject.getJSONArray("commentlist");
            for (Object o : commentList) {
                JSONObject commentJson = (JSONObject)o;
                String commentId = commentJson.getString("ReplyId");
                String likes = commentJson.getString("RUp");
                String pubTime = commentJson.getString("RReplyDate");
                pubTime = pubTime.split("\\(")[1];
                if (pubTime.contains("+")){
                    pubTime = pubTime.split("\\+")[0];
                }
                if (pubTime.contains("-")){
                    pubTime = pubTime.split("-")[0];
                }

                try {
                    CrawlerData crawlerData = CrawlerData.builder()
                            .data(crawlerRequestRecord, httpPage)
                            .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, interaction.enumVal(), commentId))
                            .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(), commentId))
                            .url((String) extras.get("articleUrl"))
                            .releaseTime(new Long(pubTime))
                            .addContentKV(Field_I_Likes,likes)
                            .resultLabelTag(interaction)
                            .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                            .build();
                    crawlerData.tagsCreator().bizTags().addSiteBiz("hao_video");
                    crawlerInteractionDataList.add(crawlerData);
                } catch (Exception e) {
                    logger.error(e.getMessage(),"parse date error");
                }
            }
        }
        return crawlerInteractionDataList;
    }

    private List<CrawlerData> washComment(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerCommentDataList = new ArrayList<>();
        HttpRequest lastRequest = crawlerRequestRecord.getHttpRequest();
        Map<String, Object> extras = lastRequest.getExtras();
        JSONObject jsonObject = JSONObject.parseObject(httpPage.getRawText());
        JSONArray commentList = jsonObject.getJSONArray("commentlist");
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");

        for (Object o : commentList) {
            JSONObject commentJson = (JSONObject)o;
            String commentId = commentJson.getString("ReplyId");
            String author = commentJson.getString("RMemberName");
            String authorId = commentJson.getString("RMemberId");
            String content = commentJson.getString("RContent");
            String floor = commentJson.getString("RFloor");
            String pubTime = commentJson.getString("RReplyDate");
            pubTime = pubTime.split("\\(")[1];
            if (pubTime.contains("+")){
                pubTime = pubTime.split("\\+")[0];
            }
            if (pubTime.contains("-")){
                pubTime = pubTime.split("-")[0];
            }
            try {
                CrawlerData crawlerCommentData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(), commentId))
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, article.enumVal(), extras.get("articleKey")))
                        .url((String) extras.get("articleUrl"))
                        .releaseTime(new Long(pubTime))
                        .addContentKV(Field_Author,author)
                        .addContentKV(Field_Author_Id,authorId)
                        .addContentKV(Field_Content,content)
                        .addContentKV(Field_Floor,floor)
                        .resultLabelTag(comment)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .build();
                crawlerCommentData.tagsCreator().bizTags().addSiteBiz("hao_video");
                crawlerCommentDataList.add(crawlerCommentData);
            } catch (Exception e) {
                logger.error(e.getMessage(),"parse date error");
            }
        }
        return crawlerCommentDataList;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    public static String unescapeHtml2J(String str){
        int times = 0;
        while (str.contains("&") && str.contains(";")){
            str = StringEscapeUtils.unescapeHtml(str);
            times ++;
            if (times > 5){
                break;
            }
        }
        return str;
    }

    private long cleanTime(String timeStr) throws ParseException {
        if (timeStr.contains("发布")){
            timeStr = timeStr.split("：")[1];
        }
        if (timeStr.contains("刚刚")){
            return System.currentTimeMillis();
        }else if (timeStr.contains("前")){
            return timeBefore(timeStr);
        }else if (timeStr.contains("-")){
            return DateUtils.parseDate(timeStr,"yyyy-MM-dd HH:mm:ss").getTime();
        }else {
            return 0;
        }

    }

    private long timeBefore(String timeStr) {
        if (timeStr.matches("\\d*天前")){
            int timeNum = Integer.parseInt(timeStr.split("天")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_DAY);

        }else if (timeStr.matches("\\d*秒前")){
            int timeNum = Integer.parseInt(timeStr.split("秒")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_SECOND);

        }else if (timeStr.matches("\\d*分钟前")){
            int timeNum = Integer.parseInt(timeStr.split("分钟")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_MINUTE);

        }else if (timeStr.matches("\\d*分钟\\d*秒前")) {
            String[] split = timeStr.split("分钟");
            int minutes = Integer.parseInt(split[0]);
            int seconds = Integer.parseInt(split[1].split("秒")[0]);
            long times = (minutes * ONE_MINUTE) + (seconds * ONE_SECOND);
            return System.currentTimeMillis() - times;

        }else if (timeStr.matches("\\d*小时前")){
            int timeNum = Integer.parseInt(timeStr.split("小时")[0]);
            return System.currentTimeMillis() - (timeNum * ONE_HOUR);

        }else if (timeStr.matches("\\d*小时\\d*分钟前")){
            String[] split = timeStr.split("小时");
            int hours = Integer.parseInt(split[0]);
            int minutes = Integer.parseInt(split[1].split("分钟")[0]);
            long times = (hours * ONE_HOUR) + (minutes * ONE_MINUTE);
            return System.currentTimeMillis() - times;

        }else {
            return 0;

        }
    }

    private static List<String> agentList = new ArrayList<>();

    static {
        agentList.add("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0; InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-IN)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)");
        agentList.add("Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/525.28.3");
        agentList.add("Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16");
        agentList.add("Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14");
        agentList.add("Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14");
        agentList.add("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0) Opera 12.14");
        agentList.add("Opera/12.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02");
        agentList.add("Opera/9.80 (Windows NT 6.1; U; es-ES) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/9.80 (Windows NT 5.1; U; zh-sg) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.2;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.1;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0");
        agentList.add("Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.13 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3756.400 QQBrowser/10.5.4043.400");
    }

    private static String getRandomUA(){
        return agentList.get(RandomUtils.nextInt(0,agentList.size() - 1));
    }
}
